<?php

namespace IDock\Insurance\LIHI\Response;

use IDock\Http\Response;
use IDock\Printer\ValidateCarCodePrinter;

class ValidateCarResponse extends AllLIHIResponse
{
    /**
     * @var ValidateCarCodePrinter $printer
     */
    public $printer = ValidateCarCodePrinter::class;

    public function resolve(): Response
    {
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return $this;
        }
        $data = json_decode($body, true);

        if ($this->printer and is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $resultMess = $data['result']['resultMessage'] ?? '';
        $success = $data['success'] ?? '';

        $result = $data['result'] ?? '';

        if (!$result) {
            $this->setError('验车码获取失败');
        }

        if (!$success) {
            $this->setError($resultMess);
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    public function printerInit(): Response
    {
        $result = $this->get('result');

        preg_match('/验车码为：(.*)/', $result, $matches);

        if ($matches[1] ?? '') {
            $this->printer->code = $matches[1];
        } else {
            $this->printer->code = '--';
        }

        return $this;
    }
}
